<template>
    <a-button @click="download()" :type="isPrimary?'primary':''" :loading="spinning"><a-icon :type="upload?'upload':'download'"/>{{name}}</a-button>
</template>
<script>
import axios from "axios"
export default {
    name:'download',
    props:{
        name:String,
        api:String,
        fileName:String,
        isPrimary:{
            type:Boolean,
            default:true
        },
        formData:Object,
        methods:{
            type:String,
            default:'get'
        },
        upload:{
            type:Boolean,
            default:true
        }
    },
    data(){
        return{
            apiUrl:window.g.apiUrl,
            spinning:false
        }
    },
    methods:{
        download(){
            this.spinning=true
            let obj={}
            if(this.methods=='get'){
                obj={
                    url: this.apiUrl+this.api,
                    params:this.formData,
                    method: this.methods,
                    responseType: 'blob'
                }
            }else{
                obj={
                    url: this.apiUrl+this.api,
                    data:this.formData,
                    method: this.methods,
                    responseType: 'blob'
                }
            }
            axios(obj).then(res=>{
                if (!res) { return }
                let url = window.URL.createObjectURL(res.data)
                let link = document.createElement('a')
                link.style.display = 'none'
                link.href = url;
                link.setAttribute('download', this.fileName)
                document.body.appendChild(link)
                link.click()
                this.spinning=false
            })
        }
    }
}
</script>